package twoD.hofem;

/**
 * A continuous range between two real numbers.
 * 
 * @author Matthias Baitsch
 */
public class Interval {

	private double lower_;
	private double upper_;

	/**
	 * Constructs an interval.
	 * 
	 * @param lower
	 *            lower bound
	 * @param upper
	 *            upper bound
	 */
	public Interval(double lower, double upper) {
		if (lower > upper) {
			throw new IllegalArgumentException("Illegal interval: [" + lower
					+ "," + upper + "]");
		}
		lower_ = lower;
		upper_ = upper;
	}

	/**
	 * Tests whether the specified value lies inside the interval.
	 * 
	 * @param x
	 *            value to test for
	 * @return <code>true</code> if l <= x <= u, <code>false</code> otherwise.
	 */
	public boolean contains(double x) {
		return lower_ <= x && x <= upper_;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		}
		if (obj instanceof Interval) {
			Interval iobj = (Interval) obj;

			return lower_ == iobj.lower_ && upper_ == iobj.upper_;
		}
		return false;
	}

	/**
	 * Returns the lower bound.
	 * 
	 * @return lower bound
	 */
	public double getLower() {
		return lower_;
	}

	/**
	 * Returns the upper bound.
	 * 
	 * @return upper bound
	 */
	public double getUpper() {
		return upper_;
	}

	@Override
	public String toString() {
		return "[" + lower_ + ", " + upper_ + "]";
	}

	/**
	 * Returns the points which divide the interval into n subintervals. For
	 * example, dividing [0, 3] into 2 subintervals returns [0, 1.5, 3].
	 * 
	 * @param n
	 *            number of subintervals
	 * @return points
	 */
	public double[] divide(int n) {
		double[] pts = new double[n + 1];
		double d = (upper_ - lower_) / n;
		pts[0] = lower_;
		pts[n] = upper_;
		for (int i = 1; i < n; i++) {
			pts[i] = lower_ + i * d;
		}
		return pts;
	}
}
